import {computed, getCurrentInstance, reactive, Ref, ref, watch} from "vue";
import {testAsyncFunc} from "@/api/test/test";

const CurrentInstance = getCurrentInstance();

interface Todo{
    id:number,
    name:string,
}

/**
 * 使用todo list
 * @param addTodoName
 * @param arrTest
 */
function useTodoList(addTodoName:Ref<string>,arrTest:number[]){
    // 清单列表
    const undoneTodoList = reactive<Todo[]>([
        {
            id: Date.now(),
            name: "吃饭",
        },
    ]);
    const addLoading=ref(false)

    // watch测试
    watch(addTodoName,(nv:string,ov:string)=>{
        console.log('val changed:',nv,ov,arrTest)
    })

    const computedTodoName=computed(()=>{
        return `<${addTodoName.value}>`
    })


    const addTodoAction = () => {
        if (addTodoName.value === ""){
            return (CurrentInstance?.refs?.todoinput as HTMLInputElement).focus();
        }
        addLoading.value=true
        const obj = {
            id: Date.now(),
            name: addTodoName.value,
        };
        addLoading.value=true
        return testAsyncFunc().then(()=>{
            undoneTodoList.push(obj);
            addTodoName.value = "";
        }).finally(()=>{
            addLoading.value=false
        })

    };

    const delTodoAction = (item: { id: number }) => {
        const index=undoneTodoList.findIndex((m:Todo) => m.id === item.id)
        undoneTodoList.splice(index,1);
    };



    return {addTodoName,computedTodoName,addTodoAction,delTodoAction,undoneTodoList,addLoading}
}

/**
 * 使用已完成列表
 * 作为参数时,自动被索引
 * @param undoneTodoList
 */
function useDoneList(undoneTodoList:Todo[]){
    // 已完成的清单列表
    const completedTodoList = reactive<Todo[]>([
        {
            id: Date.now(),
            name: "睡觉",
        },
    ]);

    const doneTodo = (item: Todo) => {
        const index:number=undoneTodoList.findIndex((m:Todo)=>m.id===item.id)
        undoneTodoList.splice(index,1);
        completedTodoList.push(item);
    };

    const delDoneAction = (item: { id: number }) => {
        const index:number=completedTodoList.findIndex((m:Todo)=>m.id===item.id)
        completedTodoList.splice(index, 1);
    };


    return {
        completedTodoList,
        doneTodo,
        delDoneAction
    }
}

export {Todo,useTodoList,useDoneList}

